//
//  RecorderTool.m
//  KeyBoard
//
//  Created by 古俊杰 on 2018/1/22.
//  Copyright © 2018年 Cocav. All rights reserved.
//

#import "RecorderTool.h"
#import <AVFoundation/AVFoundation.h>

@interface RecorderTool () <AVAudioRecorderDelegate>

@property (strong, nonatomic) NSString *recordPath;
@property (strong, nonatomic) AVAudioRecorder *recorder;
@property (assign, nonatomic) float recordedDuration;
@property (strong, nonatomic) RecorderHUD *recordHUD;
@property (strong, nonatomic) NSTimer *meterTimer;

@end

static NSTimeInterval timeInterval = 0.05;

@implementation RecorderTool

#pragma mark 录音设置
- (NSDictionary *)recorderSettings
{
    NSMutableDictionary *setting = [[NSMutableDictionary alloc] init];
    
    // 音频格式
    [setting setValue:[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
    // 音频采样率
    [setting setValue:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
    // 音频通道数
    [setting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    // 线性音频的位深度
    [setting setValue:[NSNumber numberWithInt:8]forKey:AVLinearPCMBitDepthKey];
    
    return setting;
}

//开始录音
- (BOOL)startRecordWithPath:(NSString *)recordPath
{
    [self shutRecorder:NO];
    // 1. 设置音频会话，允许录音
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    // 激活分类
    [session setActive:YES error:nil];
    
    NSURL *recordURL = [NSURL fileURLWithPath:recordPath];
    _recordPath = recordPath;
    
    NSError *error = nil;
    
    _recorder = [[AVAudioRecorder alloc] initWithURL:recordURL settings:[self recorderSettings] error:&error];
    _recorder.delegate = self;
    _recorder.meteringEnabled = YES;
    
    if ([_recorder prepareToRecord]) {
        _recordedDuration = 0.0;
        //按指定的时长开始录音
        [_recorder recordForDuration:NSTimeIntervalSince1970];
        
        _recordHUD = [[RecorderHUD alloc] initWithFrame:_parentView.bounds];
        [_parentView addSubview:_recordHUD];
        _meterTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval
                                                       target:self
                                                     selector:@selector(updateMeter)
                                                     userInfo:nil
                                                      repeats:YES];
        return YES;
    }
    return NO;
}

//录音完成
- (void)stopRecordWithCompletion:(void(^)(BOOL succeed, NSString *recordTime, NSString *recordPath))block
{
    if (_recorder && _recorder.isRecording)
    {
        _recordedDuration = _recorder.currentTime;
        
        if (_recordedDuration >= 1.0f)
        {
            //录音时常
            NSString *recordTime = [self convertTimeIntervalToStandardFormat:_recordedDuration];
            [_recorder stop];
            [self shutRecorder:NO];
            return block(YES, recordTime, _recordPath);
        }
        else {
            //录音时间太短
            RecordStatus status = RecordStatusShort;
            [[NSNotificationCenter defaultCenter] postNotificationName:RECORD_STATUS_NOTIFICATION object:@(status)];
            [self shutRecorder:YES];
            return block(NO, nil, nil);
        }
    }
    else {
        //录音失败
        RecordStatus status = RecordStatusFail;
        [[NSNotificationCenter defaultCenter] postNotificationName:RECORD_STATUS_NOTIFICATION object:@(status)];
        [self shutRecorder:YES];
        return block(NO, nil, nil);
    }
}

- (void)deleteRecordWithCompletion:(void(^)(BOOL succeed))block
{
    if (_recorder) {
        if (_recorder.isRecording) {
            [_recorder stop];
        }
        block([_recorder deleteRecording]);
        [self shutRecorder:NO];
    }
}

//关闭录音
- (void)shutRecorder:(BOOL)isShortRecord
{
    if (_recordHUD) {
        [UIView animateWithDuration:0.3 delay:(isShortRecord ? 0.6 : 0) options:UIViewAnimationOptionLayoutSubviews animations:^{
            _recordHUD.alpha = 0.0;
        } completion:^(BOOL finished) {
            [_recordHUD removeFromSuperview];
            _recordHUD = nil;
        }];
    }
    
    if (_meterTimer) {
        [_meterTimer invalidate];
        _meterTimer = nil;
    }
    
    if(_recorder){
        if (_recorder.isRecording) {
            [_recorder stop];
        }
        _recorder = nil;
    }
}

//定时监听录音变化
- (void)updateMeter
{
    if (_recordHUD && _recorder) {
        [_recorder updateMeters];
        //返回的是分贝数据，数值在-160 - 0之间
        float peakPower = [_recorder averagePowerForChannel:0];
        double ALPHA = 0.05;
        //计算x的y次方。x、y及函数值都是double型
        double peakPowerForChannel = pow(10, (ALPHA * peakPower));
        
        [_recordHUD setProgress:peakPowerForChannel];
    }
}

- (NSString *)convertTimeIntervalToStandardFormat:(double)currentTime
{
    NSString *result = @"";
    uint currentDuring = (uint)currentTime;
    uint hour = currentDuring/3600;
    currentDuring = currentDuring%3600;
    uint min = currentDuring/60;
    currentDuring = currentDuring%60;
    uint sec = currentDuring;
    if (hour) {
        result = [result stringByAppendingString:[NSString stringWithFormat:@"%@%d:", (hour < 10 ? @"0" : @""), hour]];
    }
    else {
        result = [result stringByAppendingString:@"00:"];
    }
    
    if (min) {
        result = [result stringByAppendingString:[NSString stringWithFormat:@"%@%d:", (min < 10 ? @"0" : @""), min]];
    }
    else {
        result = [result stringByAppendingString:@"00:"];
    }
    
    if (sec) {
        result = [result stringByAppendingString:[NSString stringWithFormat:@"%@%d", (sec < 10 ? @"0" : @""), sec]];
    }
    return result;
}

@end
